<?php
/**
 * Create by Phpstorm
 * User: Peco
 * Date: 2019/12/12
 * Time: 10:22
 */

namespace App\Repositories;

use App\Models\SendGroupSms;
use App\Models\SendGroupSmsLog;
use App\Models\SendVerifyCodeLog;
use App\Models\SmsSetting;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SmsRepository extends BaseRepositories
{
    /**
     * @var SendVerifyCodeLog
     */
    protected $sendVerifyCodeLog;

    /**
     * @var SmsSetting
     */
    protected $smsSetting;

    /**
     * @var SendGroupSms
     */
    protected $sendGroupSms;

    /**
     * @var SendGroupSmsLog
     */
    protected $sendGroupSmsLog;

    /**
     * SmsRepository constructor.
     * @param SendVerifyCodeLog $sendVerifyCodeLog
     * @param SmsSetting $smsSetting
     * @param SendGroupSms $sendGroupSms
     * @param SendGroupSmsLog $sendGroupSmsLog
     */
    public function __construct(SendVerifyCodeLog $sendVerifyCodeLog,
                                SmsSetting $smsSetting,
                                SendGroupSms $sendGroupSms,
                                SendGroupSmsLog $sendGroupSmsLog)
    {
        $this->sendVerifyCodeLog = $sendVerifyCodeLog;
        $this->smsSetting = $smsSetting;
        $this->sendGroupSms = $sendGroupSms;
        $this->sendGroupSmsLog = $sendGroupSmsLog;
    }

    /**
     * 添加短信配置
     * @param array $data
     * @return mixed
     */
    public function addSettingSmsRepository(array $data){
        DB::beginTransaction();
        try {

            //如果设置是默认的，则将其他的设置为非默认配置
            $this->setDefaultAndUpdate($data['key'], $data['isDefault']);

            $value = [];
            foreach ($data['configList'] as $datum){
                $value = array_merge($value,[$datum['configKey']=>$datum['configValue']]);
            }

            $value = \GuzzleHttp\json_encode($value);

            $this->smsSetting
                ->create(['key'=>$data['key'],
                    'value'=>$value,
                    'name'=>$data['name'],
                    'isDefault'=>$data['isDefault']]);

            DB::commit();
            return $this->smsSetting;

        } catch (\Exception $e) {
            DB::rollback();
            $this->response->errorInternal('添加短信配置错误：'.$e->getMessage());
        }
    }

    /**
     * 修改短信配置
     * @param array $data
     * @return mixed
     */
    public function updateSettingSmsRepository(array $data){
        DB::beginTransaction();
        try {

            //如果设置是默认的，则将其他的设置为非默认配置
            $this->setDefaultAndUpdate($data['key'], $data['isDefault']);

            $value = [];
            foreach ($data['configList'] as $datum){
                $value = array_merge($value,[$datum['configKey']=>$datum['configValue']]);
            }

            $value = \GuzzleHttp\json_encode($value);

            $sms = $this->smsSetting->findOrFail($data['id']);
            $sms->value = $value;
            $sms->key = $data['key'];
            $sms->name = $data['name'];
            $sms->isDefault = $data['isDefault'];

            $sms->saveOrFail();

            DB::commit();
            return $sms;

        } catch (\Exception $e) {
            DB::rollback();
            $this->response->errorInternal('修改短信配置：'.$e->getMessage());
        }
    }

    /**
     * 如果设置是默认的，则将其他的设置为非默认配置
     * @param string $key
     * @param int $isDefault
     * @return mixed
     */
    public function setDefaultAndUpdate(string $key, int $isDefault){
        $otherDefault =  $this->smsSetting
            ->where('isDefault', true)
            ->where('key', '!=', $key)
            ->pluck('key');

        if($isDefault && $otherDefault){
            $this->smsSetting->whereIn('key', $otherDefault)->update(['isDefault'=>false]);
        }
    }

    /**
     * @param string $key
     * @param int $isDefault
     * @return SmsSetting
     */
    public function setDefaultAndUpdateRepository(string $key, int $isDefault){
        $this->setDefaultAndUpdate($key, $isDefault);

        $this->smsSetting->where('key', $key)->update(['isDefault'=>true]);

        return $this->smsSetting;
    }

    /**
     * 短信配置分页列表
     * @param array $data
     * @param int $limit
     * @return mixed
     */
    public function settingSmsPageRepository(array $data, int $limit){
        return $this->smsSetting
            ->orderByDesc('updated_at')
            ->paginate($limit);
    }

    /**
     * 获取配置详情
     * @param $key
     * @return mixed
     */
    public function getSettingSmsDetailRepository($key){
        return $this->smsSetting->where(['key'=>$key])->firstOrFail();
    }

    /**
     * 删除短信配置
     * @param $key
     * @return mixed
     */
    public function deleteSettingSmsRepository($key){
        return $this->smsSetting->where(['key'=>$key])->delete();
    }

    /**
     * 验证key是否存在
     * @param $key
     * @return mixed
     */
    public function SettingSmsExists($key){
        return $this->smsSetting->where(['key'=>$key])->exists();
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getSettingSmsId($key){
        return $this->smsSetting->where(['key'=>$key])->pluck('id')->toArray();
    }

    /**
     * 获取短信总量
     * @return mixed
     */
    public function getSmsCountRepository(){
        return $this->sendVerifyCodeLog->count();
    }


    /**
     * 获取短信列表
     * @param array $data
     * @param int $limit
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getSmsLogPageRepository(array $data, $limit = LIMIT_PAGE){
        return $this->sendVerifyCodeLog
            ->with(['smsLogUser'])
            ->when($data['phone'], function ($q)use($data){
                $q->where('phone', $data['phone']);
            })
            ->orderByDesc('created_at')
            ->paginate($limit);
    }

    /**
     * @param array $data
     * @param array $gateways
     * @return mixed
     */
    public function sendUserSmsRepository(array $data, array $gateways){
        return $this->sendGroupSms->insertGetId([
                'type'=>data_get($data, 'type',0),
                'channel'=>data_get($gateways, 'key'),
                'content'=>$data['content'],
                'remark'=>$data['remark'],
                'created_at'=>Carbon::now(),
                'updated_at'=>Carbon::now()
            ]);
    }

    /**
     * 获取默认短信配置
     * @return mixed
     */
    public function getSettingSmsListRepository(string $key){
        return $this->smsSetting
            ->where(['key'=>$key, 'isDefault'=>true])
            ->firstOrFail();
    }

    /**
     * 群发消息列表
     * @param array $data
     * @param int $limit
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getGroupSmsPageRepository(array $data, $limit = LIMIT_PAGE){
        return $this->sendGroupSms
            ->withCount(['groupSmsLog as statusSuccess'=>function($q){
                $q->where('status', true);
            }, 'groupSmsLog as statusFail'=>function($q){
                $q->where('status', '!=', true);
            }])
            ->when($data['phone'], function ($q)use($data){
                $q->whereHas('groupSmsLog', function ($q)use($data){
                    $q->where('phone', $data['phone']);
                });
            })
            ->orderByDesc('created_at')
            ->paginate($limit);
    }

    /**
     * 群发消息列表
     * @param array $data
     * @param int $limit
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getGroupSmsLogPageRepository(array $data, $limit = LIMIT_PAGE){
        return $this->sendGroupSmsLog
            ->when($data['phone'], function ($q)use($data){
                $q->where('phone', $data['phone']);
            })
            ->where('group_sms_id', $data['group_sms_id'])
            ->orderByDesc('created_at')
            ->paginate($limit);
    }

    /**
     * @param int $id
     * @return SendGroupSmsLog|SendGroupSmsLog[]|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function getGroupSms(int $id){
        return $this->sendGroupSmsLog
            ->with('smsGroupLog')
            ->findOrFail($id);
    }

}
